package com.zbkj.admin.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.model.system.SystemAddress;
import com.zbkj.common.model.system.SystemCity;
import com.zbkj.common.model.user.User;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.TopDetail;
import com.zbkj.common.response.UserResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.CommonUtil;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.service.service.SystemAdressService;
import com.zbkj.service.service.SystemCityService;
import com.zbkj.service.service.SystemConfigService;
import com.zbkj.service.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 用户表 前端控制器
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/admin/user")
@Api(tags = "会员管理")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页显示用户表
     * @param request 搜索条件
     * @param pageParamRequest 分页参数
     */
    @PreAuthorize("hasAuthority('admin:user:list')")
    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserResponse>> getList(@ModelAttribute @Validated UserSearchRequest request,
                                                          @ModelAttribute PageParamRequest pageParamRequest) {
        CommonPage<UserResponse> userCommonPage = CommonPage.restPage(userService.getList(request, pageParamRequest));
        return CommonResult.success(userCommonPage);
    }

    /**
     * 修改用户表
     * @param id integer id
     * @param userRequest 修改参数
     */
    @PreAuthorize("hasAuthority('admin:user:update')")
    @ApiOperation(value = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult<String> update(@RequestParam Integer id, @RequestBody @Validated UserUpdateRequest userRequest) {
        userRequest.setUid(id);
        if (userService.updateUser(userRequest)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 修改用户手机号
     * @param id 用户uid
     * @param phone 手机号
     */
    @PreAuthorize("hasAuthority('admin:user:update:phone')")
    @ApiOperation(value = "修改用户手机号")
    @RequestMapping(value = "/update/phone", method = RequestMethod.GET)
    public CommonResult<String> updatePhone(@RequestParam(name = "id") Integer id, @RequestParam(name = "phone") String phone) {
        if (userService.updateUserPhone(id, phone)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 用户详情
     * @param id Integer
     */
    @PreAuthorize("hasAuthority('admin:user:info')")
    @ApiOperation(value = "详情")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<User> info(@RequestParam(value = "id") Integer id) {
        return CommonResult.success(userService.getInfoByUid(id));
    }

    /**
     * 根据参数类型查询会员对应的信息
     * @param userId Integer 会员id
     * @param type int 类型 0=消费记录，1=积分明细，2=签到记录，3=持有优惠券，4=余额变动，5=好友关系
     * @param pageParamRequest PageParamRequest 分页
     */
    @PreAuthorize("hasAuthority('admin:user:infobycondition')")
    @ApiOperation(value="会员详情")
    @RequestMapping(value = "/infobycondition", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",example = "1", required = true),
            @ApiImplicitParam(name = "type", value="0=消费记录，1=积分明细，2=签到记录，3=持有优惠券，4=余额变动，5=好友关系", example = "0"
                    , required = true)
    })
    public CommonResult<CommonPage<T>> infoByCondition(@RequestParam(name = "userId") @Valid Integer userId,
                                                       @RequestParam(name = "type") @Valid @Max(5) @Min(0) int type,
                                                       @ModelAttribute PageParamRequest pageParamRequest) {
        return CommonResult.success(CommonPage.restPage((List<T>) userService.getInfoByCondition(userId,type,pageParamRequest)));
    }

    /**
     * 会员详情页Top数据
     */
    @PreAuthorize("hasAuthority('admin:user:topdetail')")
    @ApiOperation(value = "会员详情页Top数据")
    @RequestMapping(value = "topdetail", method = RequestMethod.GET)
    public CommonResult<TopDetail> topDetail (@RequestParam @Valid Integer userId) {
        return CommonResult.success(userService.getTopDetail(userId));
    }

    /**
     * 操作积分
     */
    @PreAuthorize("hasAuthority('admin:user:operate:founds')")
    @ApiOperation(value = "积分余额")
    @RequestMapping(value = "/operate/founds", method = RequestMethod.GET)
    public CommonResult<Object> founds(@Validated UserOperateIntegralMoneyRequest request) {
        if (userService.updateIntegralMoney(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 会员分组
     * @param id String id
     * @param groupId Integer 分组Id
     */
    @PreAuthorize("hasAuthority('admin:user:group')")
    @ApiOperation(value = "分组")
    @RequestMapping(value = "/group", method = RequestMethod.POST)
    public CommonResult<String> group(@RequestParam String id, @RequestParam String groupId) {
        if (userService.group(id, groupId)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 会员标签
     * @param id String id
     * @param tagId Integer 标签id
     */
    @PreAuthorize("hasAuthority('admin:user:tag')")
    @ApiOperation(value = "标签")
    @RequestMapping(value = "/tag", method = RequestMethod.POST)
    public CommonResult<String> tag(@RequestParam String id, @RequestParam String tagId) {
        if (userService.tag(id, tagId)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    /**
     * 修改上级推广人
     */
    @PreAuthorize("hasAuthority('admin:user:update:spread')")
    @ApiOperation(value = "修改上级推广人")
    @RequestMapping(value = "/update/spread", method = RequestMethod.POST)
    public CommonResult<String> editSpread(@Validated @RequestBody UserUpdateSpreadRequest request) {
        if (userService.editSpread(request)) {
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    /**
     * 更新用户会员等级
     */
    @PreAuthorize("hasAuthority('admin:user:update:level')")
    @ApiOperation(value = "更新用户会员等级")
    @RequestMapping(value = "/update/level", method = RequestMethod.POST)
    public CommonResult<Object> updateUserLevel(@Validated @RequestBody UpdateUserLevelRequest request) {
        if (userService.updateUserLevel(request)) {
            return CommonResult.success("更新成功");
        }
        return CommonResult.failed("更新失败");
    }

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SystemCityService systemCityService;

    @Autowired
    private SystemAdressService adressService;
    /**
     * 批量添加用户
     */
    @ApiOperation(value = "批量添加用户")
    @RequestMapping(value = "/plAddUser", method = RequestMethod.POST)
    public CommonResult<Object> plAddUser(@Validated @RequestBody PlAddUserLevelRequest request) {
        Integer userNum = request.getUserNum();
        String address = generateRandomAddress(request);

        for (int i = 0; i <userNum ; i++) {
            int gender = RandomUtil.randomInt(1, 3);
            int age = RandomUtil.randomInt(35, 65);
            String name = generateRandomName(gender); // 生成随机姓名
            // 生成数量
            User user = new User();
            user.setAccount(RandomUtil.randomString(10));
            user.setPwd(CommonUtil.createPwd("123456"));
            user.setPhone(generateMaskedPhone());
            user.setUserType(Constants.USER_LOGIN_TYPE_H5);
            user.setNickname(name);
            user.setAvatar(systemConfigService.getValueByKey(Constants.USER_DEFAULT_AVATAR_CONFIG_KEY));
            //性别，0未知，1男，2女，3保密
            user.setSex(gender);
            user.setAge(age);
            Date nowDate = CrmebDateUtil.nowDateTime();
            user.setCreateTime(nowDate);
            user.setLastLoginTime(nowDate);
            user.setAddres(address);
            userService.save(user);
        }
        return CommonResult.success("操作成功");
    }
    private String generateRandomAddress( PlAddUserLevelRequest request) {
        SystemCity cityByCityId = systemCityService.getCityByCityId(request.getCity());
        String areaCode = cityByCityId.getAreaCode();
        List<SystemAddress> adressList = adressService.getList(areaCode);
        if (CollUtil.isEmpty(adressList)) {
            return "";
        }
        SystemAddress randomAddress = RandomUtil.randomEle(adressList);
        return randomAddress.getPname()+randomAddress.getCityname()+randomAddress.getAdressname(); // 假设SystemAddress有一个getFullAddress方法返回完整地址
    }

    // 生成随机手机号并替换中间5位
    private String generateMaskedPhone() {
        // 生成11位随机数字
        // 第一位固定为1
        StringBuilder sb = new StringBuilder("1");

        // 第二位从3到9之间随机选择
        int secondDigit = RandomUtil.randomInt(3, 10); // 3到9
        sb.append(secondDigit);

        // 第三位到第十一位从0到9之间随机选择
        for (int i = 0; i < 8; i++) {
            int digit = RandomUtil.randomInt(0, 10); // 0到9
            sb.append(digit);
        }

        // 生成的完整手机号
        String randomPhone = sb.toString();

        // 替换中间5位为*
        return randomPhone.substring(0, 4) + "****" + randomPhone.substring(8);
    }

    // 常见姓氏列表
    private static final List<String> LAST_NAMES = Arrays.asList(
            "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈",
            "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
            "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏",
            "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章",
            "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦",
            "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳",
            "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺",
            "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
            "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余",
            "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹",
            "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝",
            "明", "臧", "计", "顾", "穆", "萧", "尹", "姚", "邵", "湛",
            "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计"
    );
    // 生成随机姓名
    private String generateRandomName(Integer gender) {
        // 随机选择一个姓氏
        String lastName = RandomUtil.randomEle(LAST_NAMES);

        // 根据性别生成名字
        String firstName1;
        String firstName2;
        if (gender == 1) {
            // 男性名字
            firstName1 = RandomUtil.randomEle(MALE_FIRST_NAMES);
            firstName2 = RandomUtil.randomEle(MALE_FIRST_NAMES);
        } else {
            // 女性名字
            firstName1 = RandomUtil.randomEle(FEMALE_FIRST_NAMES);
            firstName2 = RandomUtil.randomEle(FEMALE_FIRST_NAMES);
        }

        // 组合姓氏和名字
        return lastName + firstName1 + firstName2;
    }

    // 常见男性名字列表
    private static final List<String> MALE_FIRST_NAMES = Arrays.asList(
            "伟", "强", "军", "勇", "洋", "超", "雷", "刚", "杰", "明",
            "波", "辉", "涛", "浩", "强", "辉", "涛", "浩", "强", "辉"
    );
    // 常见女性名字列表
    private static final List<String> FEMALE_FIRST_NAMES = Arrays.asList(
            "丽", "娜", "芳", "敏", "静", "艳", "丽", "娜", "芳", "敏",
            "静", "艳", "丽", "娜", "芳", "敏", "静", "艳", "丽", "娜"
    );


}



